import requests
import yaml  # pip install pyyaml
from loguru import logger  # pip install loguru

logger.add('logs/{time:YYYY-MM-DD}.log', level='INFO', encoding='UTF-8')

logger.info('========读取接口基础配置文件========')
# 读取yaml文件
with open('config/config.yaml', 'r') as f:
    # 读取打开的文件f 结果是字典
    config = yaml.safe_load(f)


def send_request(test_data):
    logger.info('========接口start========')
    # 想要发送请求需要请求行 头 体
    # method = 请求方法(来自test_data)
    method = test_data['method']
    # 接口地址由2部分 1-服务器地址 2-接口地址
    # url = 服务器地址(写在配置文件config.yaml中) + 接口地址(来自test_data)
    url = config['server']['test'] + test_data['url']
    # 请求头
    headers = config['headers']
    # 请求体--可能会没有body
    body = None
    if 'json' in test_data:
        body = test_data['json']
    logger.info(f'==接口request url = {url} headers = {headers} body = {body}==')
    response = requests.request(method, url, headers=headers, json=body)
    logger.info(f'==接口response 状态码 = {response.status_code} 响应体 = {response.text}')
    logger.info('========接口end========')
    return response
